package org.example.controller;

import cn.hutool.core.io.FileUtil;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import org.example.common.ResponseMessage;
import org.example.entity.Files;
import org.example.mapper.FileMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

@RestController
@RequestMapping("/file")
public class FileController {

    @Autowired
    private FileMapper fileMapper;

    private static final String ROOT_PATH = System.getProperty("user.dir") + File.separator + "files";

    /***
     * 文件上传
     * @param file
     * @return
     */
    @PostMapping("/upload")
    public ResponseMessage upload(MultipartFile file, Files files) throws IOException {
        // aaa.png
        String originalFilename = file.getOriginalFilename();   // 文件的原始名称
        String mainName = FileUtil.mainName(originalFilename);  // aaa
        String extName = FileUtil.extName(originalFilename);// png
        File parentFile = new File(ROOT_PATH);
        if (!FileUtil.exist(ROOT_PATH)){
            FileUtil.mkdir(ROOT_PATH);    // 如果当前文件的父级目录不存在，就创建
        }
        if (FileUtil.exist(ROOT_PATH + File.separator + originalFilename)){
            originalFilename = System.currentTimeMillis() + "_" + mainName + "." +extName;
        }
        File saveFile = new File(ROOT_PATH + File.separator + originalFilename);
        file.transferTo(saveFile);  // 存储文件到本地磁盘里面
        String url = "http://localhost:8088/file/download/" + originalFilename;
        files.setNumber(files.getNumber());
        files.setAvatar(url);
        fileMapper.uploadFiles(files);
        return ResponseMessage.success(url);//返回文件的链接，这个链接就是文件的下载地址，这个下载地址就是后台提供的
    }

    /***
     * 文件下载
     * @param fileName
     * @throws IOException
     */
    @GetMapping("/download/{fileName}")
    public void download(@PathVariable String fileName, HttpServletResponse response) throws IOException {
        String filePath = ROOT_PATH + File.separator + fileName;
        if (!FileUtil.exist(filePath)){
            return;
        }
        byte[] bytes = FileUtil.readBytes(filePath);
        ServletOutputStream outputStream = response.getOutputStream();
        outputStream.write(bytes); //数组是一个字节数组，也是文件的字节流数组
        outputStream.flush();
        outputStream.close();
    }
}
